package util

import (
	"encoding/json"
	"log"
	"os"
	"sync"

	"htgis/monitor/common/file"
	"htgis/monitor/module/agent/model"
)

var (
	// ConfigFile path
	ConfigFile string
	config     *model.GlobalConfig
	lock       = new(sync.RWMutex)
)

// Config returns configuration
func Config() *model.GlobalConfig {
	lock.RLock()
	defer lock.RUnlock()
	return config
}

// Hostname returns hostname
func Hostname() (string, error) {
	hostname := Config().Hostname
	if hostname != "" {
		return hostname, nil
	}

	hostname, err := os.Hostname()
	if err != nil {
		log.Println("ERROR: os.Hostname() fail", err)
	}
	return hostname, err
}

// IP returns ip
func IP() string {
	ip := Config().IP
	if ip != "" {
		// use ip in configuration
		return ip
	}

	if len(LocalIP) > 0 {
		ip = LocalIP
	}

	return ip
}

// ParseConfig parses config struct
func ParseConfig(cfg string) {
	if cfg == "" {
		log.Fatalln("use -c to specify configuration file")
	}
	if !file.IsExist(cfg) {
		log.Fatalln("config file:", cfg, "is not existent. maybe you need `mv cfg.example.json cfg.json`")
	}

	ConfigFile = cfg

	configContent, err := file.ToTrimString(cfg)
	if err != nil {
		log.Fatalln("read config file:", cfg, "fail:", err)
	}

	var c model.GlobalConfig
	err = json.Unmarshal([]byte(configContent), &c)
	if err != nil {
		log.Fatalln("parse config file:", cfg, "fail:", err)
	}

	lock.Lock()
	defer lock.Unlock()

	config = &c

	log.Println("read config file:", cfg, "successfully")
}
